import Vue from 'vue'
import Confirm from './confirm.vue'
import pageScroll from '../../../_common/js/utils/pageScroll'
Confirm.new = (options = {}, okCallback, cancelCallback) => {
  options.buttons = options.buttons || [{
    text: '取消',
    click: cancelCallback
  }, {
    text: '确定',
    color: true,
    click: okCallback
  }]

  const instance = new Vue({
    data: options,
    render (h) {
      return h(Confirm, {
        props: options
      })
    }
  })
  const component = instance.$mount()
  document.body.appendChild(component.$el)
  pageScroll.lock(component.$el)

  const confirm = instance.$children[0]
  function hashChange () {
    pageScroll.unlock()
    const el = confirm.$el
    el.parentNode && el.parentNode.removeChild(el)
  }
  window.addEventListener('hashchange', hashChange)

  confirm.closeAlert = (button) => {
    const el = confirm.$el
    pageScroll.unlock(el)
    el.parentNode && el.parentNode.removeChild(el)
    window.removeEventListener('hashchange', hashChange)
    typeof confirm.callback === 'function' && confirm.callback(button)
    button.click && button.click()
  }
}

export default Confirm
